"""
配置文件
"""
import os
from enum import Enum
from typing import Literal
from dotenv import load_dotenv
from pydantic import BaseSettings, Field, validator

# 加载环境变量
load_dotenv()

class ModelType(str, Enum):
    OPENAI = "openai"
    LOCAL = "local"
    GGUF = "gguf"  # 添加GGUF模型类型

class Settings(BaseSettings):
    # 模型配置
    model_type: ModelType = Field(ModelType.OPENAI, env="MODEL_TYPE")
    
    # OpenAI 配置
    openai_api_key: str = Field("", env="OPENAI_API_KEY")
    openai_api_base: str = Field("https://api.openai.com/v1", env="OPENAI_API_BASE")
    openai_api_type: str = Field("open_ai", env="OPENAI_API_TYPE")
    openai_api_version: str = Field("", env="OPENAI_API_VERSION")
    openai_model: str = Field("gpt-3.5-turbo", env="OPENAI_MODEL")
    
    # 本地模型配置
    local_llm_model: str = Field("gpt2", env="LOCAL_LLM_MODEL")
    local_embedding_model: str = Field("sentence-transformers/all-MiniLM-L6-v2", 
                                     env="LOCAL_EMBEDDING_MODEL")
    # GGUF模型配置
    gguf_model_path: str = Field("", env="GGUF_MODEL_PATH")
    gguf_n_ctx: int = Field(2048, env="GGUF_N_CTX")  # 上下文长度
    gguf_n_threads: int = Field(0, env="GGUF_N_THREADS")  # 0表示自动选择
    gguf_n_gpu_layers: int = Field(0, env="GGUF_N_GPU_LAYERS")  # 0表示不使用GPU
    
    device: str = Field("cuda" if torch.cuda.is_available() else "cpu", 
                       env="DEVICE")
    
    # 向量数据库配置
    persist_directory: str = Field("./data/vector_store", env="PERSIST_DIRECTORY")
    collection_name: str = Field("documents", env="COLLECTION_NAME")
    
    # 应用配置
    debug: bool = Field(True, env="DEBUG")
    host: str = Field("0.0.0.0", env="HOST")
    port: int = Field(7860, env="PORT")
    
    # 安全配置
    secret_key: str = Field("your-secret-key-123", env="SECRET_KEY")
    algorithm: str = Field("HS256", env="ALGORITHM")
    access_token_expire_minutes: int = Field(30, env="ACCESS_TOKEN_EXPIRE_MINUTES")
    
    @validator('model_type', pre=True)
    def validate_model_type(cls, v):
        if isinstance(v, str):
            return ModelType(v.lower())
        return v
    
    class Config:
        env_file = ".env"
        env_file_encoding = 'utf-8'
        
    def is_local_model(self) -> bool:
        return self.model_type == ModelType.LOCAL
    
    class Config:
        env_file = ".env"
        env_file_encoding = 'utf-8'

# 全局配置实例
settings = Settings()

# 确保必要的目录存在
os.makedirs(settings.persist_directory, exist_ok=True)
os.makedirs("./data/uploads", exist_ok=True)
